import json
import os

from flask import request, Blueprint, jsonify, current_app

from utils.http import success_api, fail_api
from utils.mysql_util import MySQLConnPool

# 数据库链接
DB = MySQLConnPool()
DB.connect()

# 创建蓝图对象
auth_blueprint = Blueprint('auth', __name__)


@auth_blueprint.route('/auth/login', methods=['POST'])
def login():
    # 获取用户名和密码
    username = request.form.get('username')
    password = request.form.get('password')

    base_data = DB.select(table='users', fields=['password'], where=f'username = "{username}"')
    # 进行用户名和密码的验证逻辑，这里只是示例，你可以根据实际情况进行修改
    if base_data:
        # 登录成功
        if base_data[0]["password"] == password:
            return success_api(msg="登录成功")
        else:
            return fail_api(msg='密码错误')
    else:
        # 登录失败
        return fail_api(msg='密码错误/没有用户')


@auth_blueprint.route('/auth/register', methods=['POST'])
def register():
    username = request.form.get('username')
    password = request.form.get('password')
    print(username)
    print(password)
    data = {"username": username, "password": password}
    # 在这里编写你的注册逻辑，可以将用户名和密码存储到数据库中
    DB.insert(table='users', data=data)
    # 假设注册成功，返回成功的响应
    return success_api(msg='注册成功')


@auth_blueprint.route('/auth/navs', methods=['GET'])
def load_navs():
    """
    加载菜单
    :return:
    """
    file_path = os.path.join(current_app.static_folder, 'data', 'navs.json')
    with open(file_path, 'r', encoding='utf-8') as f:
        navs = json.load(f)
        f.close()

    return jsonify(navs)
